﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class panel_Currency : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private SqlConnection masterConnection;
        
        public panel_Currency()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.masterConnection = new SqlConnection(mySetting.DB2ConnectionString);

            LoadData();

            this.Currency.DoubleClick += Currency_DoubleClick;
            this.Currency.PopupMenuShowing += Currency_PopupMenuShowing;
            this.currencyContext.ItemClicked += currencyContext_ItemClicked;
        }

        private void callEditForm()
        {
            DataRow row = Currency.GetFocusedDataRow();
            frm_Edit_Currency editForm = new frm_Edit_Currency();
            editForm.currency_id = row[0].ToString();
            if (editForm.LoadData())
            {
                //editForm.Show();
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Cannot load data for selected record");
            }
        }

        void Currency_DoubleClick(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        void currencyContext_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.currencyContext.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "editSelection":
                    callEditForm();
                    break;
                case "importSelection":
                    importDatabase();
                    break;
                case "addSelection":
                    frm_Add_Currency add_Form = new frm_Add_Currency();                    
                    add_Form.ShowDialog();
                    LoadData();
                    break;
                case "deleteSelection":
                    deleteRecord();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void Currency_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.currencyContext.Show(MousePosition);
        }

        private void LoadData()
        {
            DataSet sourceDataSet = new DataSet();
            INISettings mySettings = new INISettings();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySettings.SQLConnectionString;
            string sql = "SELECT * FROM [222_Currency]";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridCurrency.DataSource = sourceDataSet.Tables[0];
                getUpdateInfo();
            }
            else
            {
                MessageBox.Show("There is no data for Currency");
                DataTable newTable = new DataTable();
                newTable.Columns.Add("CurrencyID", typeof(int));
                newTable.Columns.Add("CurrencyName", typeof(string));
                newTable.Columns.Add("CurrencySymbol", typeof(string));
                gridCurrency.DataSource = newTable;
            }
            Currency.Columns[0].Caption = "Currency ID";
            Currency.Columns[1].Caption = "Currency Name";
            Currency.Columns[2].Caption = "Currency Symbol";
            Currency.Columns[0].Visible = false;
            Currency.BestFitColumns();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            frm_Add_Currency add_Form = new frm_Add_Currency();
            //add_Form.Show();
            add_Form.ShowDialog();
            LoadData();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            deleteRecord();
        }

        private void deleteRecord()
        {
            int[] rows = Currency.GetSelectedRows();
            if (rows.Length <= 0)
            {
                MessageBox.Show("There is no selected record to delete");
            }
            else
            {
                if (MessageBox.Show("Are you really to delete selected records now?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string[] id_list = new string[rows.Length];
                    for (int i = 0; i < rows.Length; i++)
                    {
                        DataRow selected_row = Currency.GetDataRow(rows[i]);
                        id_list[i] = "'" + selected_row[0].ToString() + "'";
                    }
                    string id = string.Join(",", id_list);

                    try
                    {
                        myConnection.Open();
                        string sql = "DELETE [222_Currency] WHERE CurrencyID IN (" + id + ")";
                        SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                        cmd_sql.ExecuteNonQuery();
                        cmd_sql.Dispose();
                        myConnection.Close();
                        MessageBox.Show("Currency deleted success.");
                        LoadData();
                    }
                    catch //(Exception ex)
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                        //MessageBox.Show(ex.Message);
                        MessageBox.Show("Cannot delete Currency. Please try again.");
                    }
                }
            } 
        }

        /////////////////////////////////////
        /// Get Update Information
        /////////////////////////////////////
        private void getUpdateInfo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT LastUpdate FROM [222_UpdateHistory] WHERE ID=14";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.updateDate.Text = dataReader["LastUpdate"].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get update information");
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            importDatabase();
        }

        ////////////////////////////////////
        /// Update database From AS400
        ////////////////////////////////////
        private void importDatabase()
        {
            DataSet as400 = new DataSet();
            DataSet currency = new DataSet();
            string sql = null;
            SqlCommand cmd;
            SqlDataAdapter adapter;
            DataTable currency_db2;
            DataTable currency_local;
            try
            {
                //Get Data From AS400
                masterConnection.Open();
                sql = "SELECT * FROM OPENQUERY(AS400_MPFLIB, 'SELECT DMKBN, DMTNAM FROM MPDM00')";
                cmd = new SqlCommand(sql, masterConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(as400);
                currency_db2 = as400.Tables[0];
                adapter.Dispose();
                cmd.Dispose();
                masterConnection.Close();

                //Get Data From Local Database
                Dictionary<string, string> symbol = new Dictionary<string, string>() {{"B", "THB"}, {"W", "KRW"}, {"D", "VND"},
                    {"E", "EUR"}};
                myConnection.Open();
                sql = "SELECT * FROM [222_Currency]";
                cmd = new SqlCommand(sql, myConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(currency, "222_Currency");
                currency_local = currency.Tables["222_Currency"];

                foreach (DataRow as400_row in currency_db2.Rows)
                {
                    
                    string as400_symbol = "";
                    if (symbol.ContainsKey(as400_row["DMKBN"].ToString()))
                    {
                        as400_symbol = symbol[as400_row["DMKBN"].ToString()];
                    }
                    else
                    {
                        as400_symbol = "JPY";
                    }

                    DataRow[] current_row = currency_local.Select("CurrencySymbol='" + as400_symbol + "'");
                    if (current_row.Length == 0)
                    {
                        DataRow new_row = currency_local.NewRow();
                        new_row["CurrencyName"] = as400_row["DMTNAM"].ToString();
                        new_row["CurrencySymbol"] = as400_symbol;                        
                        currency_local.Rows.Add(new_row);
                    }
                }

                SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(adapter);
                //Update to Local Database
                adapter.Update(currency, "222_Currency");

                adapter.Dispose();
                cmd.Dispose();
                myConnection.Close();

                //Update History
                myConnection.Open();
                sql = "UPDATE [222_UpdateHistory] SET LastUpdate=GETDATE() WHERE ID=14";
                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                cmd_sql.ExecuteNonQuery();
                cmd_sql.Dispose();
                myConnection.Close();

                LoadData();

                MessageBox.Show("Database has been updated successfull.");

            }
            catch (Exception ex)
            {
                if (masterConnection.State == ConnectionState.Open)
                {
                    masterConnection.Close();
                }

                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot connect to AS400");
            }
        }
    }
}
